<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true"
             :model="formInline"
             class="el-form query-form el-form--label-right el-form--inline">
      <!-- 部门名称 -->
      <el-form-item label="部门名称">
        <el-input size="small"
                  v-model="formInline.dept_name"
                  placeholder="请输入">
        </el-input>
      </el-form-item>
      <!-- 所属公司 -->
      <el-form-item label="所属公司">
        <el-input size="small"
                  v-model="formInline.company_name"
                  placeholder="请输入">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small"
                   type="primary"
                   @click="onSearch"
                   icon="el-icon-search">搜 索
        </el-button>
        <el-button size="small"
                   type="default"
                   @click="handleAdd"
                   icon="el-icon-plus">添 加
        </el-button>
        <el-button size="small"
                   type="primary"
                   @click="handleDelete()"
                   icon="el-icon-delete"
                   v-if="isMoreDel">
          批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData"
              style="margin-top:30px"
              row-key="id"
              :tree-props="{children: 'children'}"
              @selection-change="handleSelectionChange"
              reserve-selection="true">
      <el-table-column type="selection"
                       width="50"
                       fixed="left"></el-table-column>
      <el-table-column prop="id"
                       label="ID"></el-table-column>
      <el-table-column prop="title"
                       label="部门名称"></el-table-column>
      <el-table-column prop="num"
                       label="排序"></el-table-column>
      <el-table-column prop="type"
                       label="节点类型"
                       :formatter="formatType"></el-table-column>
      <el-table-column prop="depot_type"
                       label="仓库类型"
                       :formatter="formatDepotType"></el-table-column>
      <!-- <el-table-column prop="is_appointment"
                       label="开通预约"
                       :formatter="formatIsAppointment"></el-table-column> -->
      <el-table-column label="操作"
                       width="250"
                       fixed="right">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="default"
                     @click="handleEdit(scope.$index, scope.row)">
            编辑</el-button>
          <el-button size="mini"
                     type="primary"
                     @click="handleDelete(scope.$index, scope.row)">
            删除</el-button>
          <el-button size="mini" type="default" @click="handleSetting(scope.$index, scope.row)">
                        设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加-編輯窗口 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="centerDialogVisible"
               width="40%"
               center
               custom-class="center_dislog">
      <el-form ref="editForm"
               :model="editForm"
               label-width="100px">
        <!-- 部门名称 -->
        <el-form-item label="部门名称"
                      prop="DeptName">
          <el-input v-model="editForm.DeptName"></el-input>
        </el-form-item>
        <!-- 父级部门 -->
        <el-form-item label="父级部门">
          <el-tree style="max-height:200px;overflow-y: auto;"
                   :data="deptData"
                   show-checkbox
                   node-key="id"
                   :props="defaultProps"
                   ref="tree"
                   :default-expanded-keys="deptDefaule"
                   :default-checked-keys="deptDefaule" 
                   @check="handleNodeCheck"
                   class="myDialogTree"
                   :check-strictly="true">
          </el-tree>
        </el-form-item>
        <el-form-item label="节点类型"
                      prop="Type">
          <el-select v-model="editForm.Type"
                     placeholder="请选择"
                     @change="typeChange">
            <el-option label="根"
                       value="0"></el-option>
            <el-option label="分公司"
                       value="1"></el-option>
            <el-option label="厂房"
                       value="2"></el-option>
            <el-option label="仓库"
                       value="3"></el-option>
            <el-option label="库位"
                       value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库类型"
                      prop="DeptType">
          <el-select v-model="editForm.DeptType"
                     placeholder="请选择">
            <el-option label="无"
                       value="0"></el-option>
            <el-option label="总仓"
                       value="1"></el-option>
            <el-option label="DC"
                       value="2"></el-option>
            <el-option label="外库"
                       value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库编号" v-if="editForm.Type == 3">
              <el-input v-model="editForm.DeliveryLoc"></el-input>
        </el-form-item>
        <!-- 排序 -->
        <el-form-item label="排序"
                      prop="SortNum">
          <el-input v-model="editForm.SortNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   :disabled="editDisabled"
                   @click="updateSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="设置"
               :visible.sync="centerDialogSetting"
               width="40%"
               center
               custom-class="center_dislog">
      <el-form ref="settingForm"
               :model="settingForm"
               label-width="140px">
        <!-- 公司名称 -->
        <el-form-item label="公司全称"
                      prop="full_name">
          <el-input v-model="settingForm.full_name"></el-input>
        </el-form-item>
        <el-form-item label="公司简称"
                      prop="simple_name">
          <el-input v-model="settingForm.simple_name"></el-input>
        </el-form-item>
        <!-- 所属公司 -->
        <el-form-item label="所属公司" >
          <el-select v-model="settingForm.company_id"
                     placeholder="请选择"
                     filterable>
             <el-option label="暂不选择" :value="0">
            </el-option>
            <el-option v-for="(item) in company_list"
                       :key="item.id"
                       :label="item.company_name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 仓库编号 -->
        <!-- <el-form-item label="仓库编号">
          <el-select v-model="settingForm.settle_office_sn"
                     placeholder="请选择"
                     filterable>
            <el-option v-for="(item,index) in office_list"
                       :key="index"
                       :label="item.delivery_location + '-' + item.settle_office"
                       :value="item.settle_office_sn"
                       :data-id="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="centerDialogSetting = false">取 消</el-button>
        <el-button type="primary"
                   :disabled="addDisabled"
                   @click="settingSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
import {
  mapState
} from 'vuex'
import {
  deptList,
  deptAdd,
  deptEdit,
  getCompany,
  deptDelete,
  companyList
} from '../../api.js'
export default {
  name: "systemFramework",
  data () {
    return {
      isAdd: true,
      dialogTitle: '',
      isMoreDel: false,
      isSnShow: false,
      multipleSelection: [],
      centerDialogVisible: false,
      centerDialogSetting: false,
      breadcrumbName: '',
      breadcrumbPath: '',
      breadcrumbNameP: '',
      tableData: [],
      deptDefaule:[],
      editForm: {
        DeptId: '',
        DeptName: '',
        Pid: '',
        Type: '',
        SortNum: '',
        DeptType: '',
        Level: '',
        DeliveryLoc:'',
      },
      company_list: [],
      office_list: [],
      settingForm: {
        dept_id:'',
        full_name:'',
        simple_name:'',
        company_id:'',
        company_name:'',
      },
      // 属性图数据
      deptData: [],
      snData: [],
      storageData: [],
      checkedStorage: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      //分页
      total: 0,
      //查询栏默认展示数据
      formInline: {
        dept_name: '',
        company_name: ''
      },
      editDisabled: false,
      addDisabled: false,
    }
  },
  mounted () {
    this.breadcrumbName = this.$route.query.breadcrumbName
    this.breadcrumbPath = this.$route.query.breadcrumbPath
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP
    this.getTableDate(this.formInline);
    this.getCompanyList();
  },
  methods: {
    //获取表格数据
    getTableDate (searchObj) {
      var _this = this;
       deptList(searchObj).then(res => {
          if (res.ErrorCode == 0) {
              _this.tableData = res.Data
              _this.deptData = res.Data
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
    },
    getCompanyList () {
      var _this = this;
      companyList().then(res => {
          if (res.ErrorCode == 0) {
              _this.company_list= res.Data.list
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
    },
    
    getStorageList (dept_id) {
      var _this = this;
      axios({
        method: 'post',
        baseURL: _this.baseUrl,
        url: 'admin/dept/storage',
        data: {
          access_token: _this.access_token,
          dept_id: dept_id
        }
      })
        .then(function (response) {
          var res = response.data
          if (res.ErrorCode == 0) {
            _this.storageData = res.Data
            _this.checkedStorage = []
            _this.storageData.forEach(item => {
              if (item.dept_id == dept_id) {
                _this.checkedStorage.push(item.id)
              }
            })
          } else {
            _this.$message.error(res.ErrorMsg);
          }
        })
        .catch(function (error) {
          _this.$message.error(error);
        });
    },
    //表格查询
    onSearch () {
      this.getTableDate(this.formInline);
    },
    //添加
    handleAdd () {
      var _this = this;
      this.isAdd = true;
      this.dialogTitle = '添 加';
      this.centerDialogVisible = true;
      for (var k in this.editForm) {
        this.editForm[k] = ''
      }
      setTimeout(function () {
        _this.$refs.tree.setCheckedKeys([])
      }, 50)

    },
    //表格的操作
    //编辑
    handleEdit (index, row) {
      var _this = this;
      this.isAdd = false;
      this.centerDialogVisible = true;
      this.dialogTitle = '编 辑';
      this.editForm.DeptId = row.id
      this.editForm.DeptName = row.title
      this.editForm.Pid = row.pid
      this.editForm.Type = row.type+''
      this.editForm.SortNum = row.num
      this.editForm.DeptType = row.depot_type+''
      this.editForm.DeliveryLoc = row.depot_code
      setTimeout(function () {
        _this.$refs.tree.setCheckedKeys([row.pid])
        _this.deptDefaule = [row.pid]
      }, 50)
    },
    updateSubmit () {
      this.editDisabled = true;
      var _this = this;
      this.editForm.Type = this.editForm.Type*1
      this.editForm.DeptType = this.editForm.DeptType*1
      var data={
        title:_this.editForm.DeptName,
        type:this.editForm.Type,
        pid:this.editForm.Pid,
        num:this.editForm.SortNum,
        depot_type: this.editForm.DeptType,
        depot_code:this.editForm.DeliveryLoc
      }
       if (_this.isAdd) {
      deptAdd(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.editDisabled = false;
            _this.centerDialogVisible = false;
            _this.checkedStorage = [];
            _this.$message.success("添加成功");
            _this.getTableDate(_this.formInline);
            _this.$refs.tree.setCheckedKeys([])
          } else {
            _this.editDisabled = false;
            this.$message.error(res.ErrorMsg);
          }
        })
       }else{
        data.id = this.editForm.DeptId
         deptEdit(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.editDisabled = false;
            _this.centerDialogVisible = false;
            _this.checkedStorage = [];
            _this.$message.success("编辑成功");
            _this.getTableDate(_this.formInline);
            _this.$refs.tree.setCheckedKeys([])
          } else {
            _this.editDisabled = false;
            this.$message.error(res.ErrorMsg);
          }
        })
       }
    },
    //删除
    handleDelete (index, row) {
      var _this = this
      var del_ids = []
      if (row) {
        del_ids.push(row.id)
      } else {
        _this.multipleSelection.forEach(function (item) {
          del_ids.push(item.id)
        })
        _this.multipleSelection = []
        _this.isMoreDel = false
      }
      console.log("del_ids",del_ids);
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
        let dataArr= {
          id: del_ids
        }
         deptDelete(dataArr).then(res => {
          if (res.ErrorCode == 0) {
            _this.getTableDate(_this.formInline);
            _this.$message.success("删除成功");
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      }).catch(() => {

      });
    },
    //选中表格数据
    handleSelectionChange (val) {
      if (val.length == 0) {
        this.isMoreDel = false
      } else {
        this.isMoreDel = true
      }
      this.multipleSelection = val
    },
    handleSetting (index, row) {
      console.log("bbb",index, row)
      var _this = this;
      this.centerDialogSetting = true
      _this.settingForm.dept_id = row.id
      _this.settingForm.full_name = row.full_name
      _this.settingForm.simple_name = row.simple_name
      _this.settingForm.company_id = row.company_id
    },
    settingSubmit () {
      this.addDisabled = true;
      var _this = this;
      getCompany(_this.settingForm).then(res => {
        if (res.ErrorCode == 0) {
           _this.getTableDate(_this.formInline);
           _this.$message.success(res.ErrorMsg);
            _this.addDisabled = false;
            _this.centerDialogSetting = false;
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
      // var dataObj = JSON.parse(JSON.stringify(_this.settingForm)) ;
      //  if( dataObj.CompanyId == ''){
      //     dataObj.CompanyId = 0
      // }
      // deptEdit(dataObj).then(res => {
      //     if (res.code == 0) {
      //         _this.$message.success("设置成功");
      //         _this.addDisabled = false;
      //         _this.centerDialogSetting = false;
      //         _this.getTableDate(_this.formInline);
      //     } else {
      //       this.$message.error(res.ErrorMsg);
      //         _this.addDisabled = false;
      //     }
      //   })
    },
    handleNodeCheck (node, checked, indeterminate) {
      //  handleDeptAddNodeCheck(data, checked, indeterminate) {
      //   if (checked.checkedKeys != []) {
      //     this.$refs.dept_tree.setCheckedKeys([data.id])
      //     this.addForm["PlaceDeptId"] = data.id
      //   }
      // },
      console.log("1212",node, checked, indeterminate)
      if (checked.checkedKeys != []) {
        this.editForm.Pid = node.id;
        this.editForm.Level = node.level
        // this.editForm.pids = node.pids + ',[' + node.id + ']';
        this.$refs.tree.setCheckedKeys([node.id])
        // this.editForm.storageIds = []

        if (this.editForm.type == 4) {
          this.getStorageList(node.id)
        }
      }
    },
    //选择库位
    handleCheckedStorageChange (value) {
      this.checkedStorage = value
    },
    // 节点类型为仓库时  请求结算办公室数据
    typeChange (val) {
      // if (val == 3) {
      //   this.isSnShow = true
      //   this.getSnList()
      // }
    },
    //表格数据处理
    formatType (row, column, cellValue) {
      if (cellValue == 0) {
        return '根'
      } else if (cellValue == 1) {
        return '分公司'
      } else if (cellValue == 2) {
        return '厂房'
      } else if (cellValue == 3) {
        return '仓库'
      } else if (cellValue == 4) {
        return '库位'
      }
    },
    formatDepotType (row, column, cellValue) {
      if (cellValue == 0) {
        return '无'
      } else if (cellValue == 1) {
        return '总仓'
      } else if (cellValue == 2) {
        return 'DC'
      } else if (cellValue == 3) {
        return '外库'
      }
    },
    formatIsAppointment (row, column, cellValue) {
      if (cellValue == 0) {
        return '否'
      } else if (cellValue == 1) {
        return '是'
      }
    },
  },
  computed: {
    ...mapState({
      access_token: state => state.access_token,
      baseUrl: state => state.baseUrl,
    }),
  },
}
</script>
<style scoped>
.el-checkbox-group .el-checkbox {
  margin-left: 0;
}
</style>